package org.upt.dcda.webservices;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.upt.dcda.AuthorManagerBeanRemote;
import org.upt.dcda.db.AuthorEntity;

@Path("/services/authors/")
public class AuthorServices extends CommonService
{

	@GET
	@Path("get")
	@Produces("application/json")
	public String getAuthors() throws Exception
	{
		try
		{
			final List<Author> authors = new ArrayList<Author>();

			for (AuthorEntity author : getAuthorManagerBean().getAllAuthors())
			{
				authors.add(new Author(author.getAuthorId(), author
						.getAuthorName()));
			}

			return gson.toJson(authors);
		}
		catch (Throwable t)
		{
			logger.error("Caught " + t.getClass() + ": " + t, t);
			throw new Exception("Cannot complete request");
		}
	}

	@GET
	@Path("add")
	@Produces("text/plain")
	public String addAuthor(@QueryParam("name") String name,
			@QueryParam("info") String info) throws Exception
	{
		gson.fromJson(info, List.class);
		return gson.toJson(true);
	}

	@GET
	@Path("getInfo")
	public String getInfo(@QueryParam("id") int authorId) throws Exception
	{
		AuthorManagerBeanRemote authorMan;
		try
		{
			authorMan = getAuthorManagerBean();
			AuthorEntity author = authorMan.getAuthorById(authorId);
			AuthorWithInfo result = new AuthorWithInfo(author.getAuthorId(),
					author.getAuthorName(), author.getAuthorInfo());
			return gson.toJson(result);
		}
		catch (Throwable t)
		{
			logger.error("Caught " + t.getClass() + ": " + t, t);
			throw new Exception("Cannot complete request");
		}
	}

	private class Author
	{

		@SuppressWarnings("unused")
		public final int	id;

		@SuppressWarnings("unused")
		public final String	name;

		public Author(int id, String name)
		{
			this.id = id;
			this.name = name;
		}
	}

	private class AuthorWithInfo extends Author
	{
		@SuppressWarnings("unused")
		public final String	info;

		public AuthorWithInfo(int id, String name, String info)
		{
			super(id, name);
			this.info = info;
		}
	}
}
